from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound

from zope.interface import implements

from repoze.who.interfaces import IAuthenticator, IMetadataProvider, IChallenger

import papyrus.lib.helpers as h
from papyrus.model import meta, User


class PapyrusRepozeWhoPlugin(object):
    """repoze.who Papyrus plugin.

    This plugin acts as:
    * an authenticator
    * a metadata provider
    """

    implements(IAuthenticator, IMetadataProvider, IChallenger)

    # Authenticator
    def authenticate(self, environ, identity):
        login = identity.get("login")
        password = identity.get("password")

        if not (login and password):
            return

        login = login.decode("utf-8")
        password = password.decode("utf-8")

        try:
            user = meta.Session.query(User).filter_by(email=login, password=password).one()
        except (NoResultFound, MultipleResultsFound):
            return
        else:
            return user.id

    # Metadata provider
    def add_metadata(self, environ, identity):
        id = identity.get("repoze.who.userid")

        user = meta.Session.query(User).get(id)
        identity.update({"user": user})
#        environ["repoze.what.credentials"] = {
#            "repoze.what.userid":identity['repoze.who.userid'],
#        }
